<template>
  <div class="hello">
    <div>ws测试</div>
    <div>
      ping : <span class="ping">{{ ping }}</span>  | pong: <span class="ping">{{ pong }}</span> 

      <input type="button" value="pingpong" @click="pingpong" />
    </div>
    <input type="text" v-model="input" />

    <input type="button" value="发送" @click="sendmsg" />
  </div>
</template>

<script>
import { getStudentList, getStudentInfo } from "../api/student";
import protoRoot from "@/proto/proto.js";
import protobuf from "protobufjs";
import lodash from "lodash";


function isArrayBuffer(obj) {
  return Object.prototype.toString.call(obj) === '[object ArrayBuffer]'
}


export default {
  data() {
    return {
      list: "null",
      info: "null",
      wsob: null,
      input: "说话啊",
      ping:0,
      pong:0,
      ping_start:0
    };
  },
  name: "HelloWorld",
  methods: {
    pingpong(){
      // 进行一次 ping & pong
      this.ping_start=new Date().getTime();
      for(let a=1;a<100;a++){
          this.pingpong2();
      }
      
    },
    pingpong2(){
      let buffer = this.createreq({ping:{}});
      this.wsob.send(buffer)
    },
    onopen() {},
    onmessage(rawResponse) {
      let a = this.transformResponse(rawResponse);
    },
    onerror() {},
    onclose() {},
    onPing(ping,decodedResponse){
      let timestamp = new Date().getTime();
      this.ping = timestamp - decodedResponse.timestamp;
    },
    onPong(pong,decodedResponse){
      // 收到服务器的 pong 
      this.pong = decodedResponse.timestamp- this.ping_start;
    },
    transformResponse(blob) {
        // 判断response是否是arrayBuffer
        console.log("数据:", blob);
        var reader = new FileReader()
 
        reader.readAsArrayBuffer(blob)
        reader.onload =(event)=>{
          let rawResponse = event.target.result;
          // let rawResponse  = new Uint8Array(arrayBufferNew);
          if (rawResponse == null || !isArrayBuffer(rawResponse)) {
            console.log("不是isArrayBuffer",rawResponse);
            return rawResponse
          }
          try {
            const buf = protobuf.util.newBuffer(rawResponse)
            // decode响应体
            const decodedResponse =  protoRoot.lookup("pb.app.MessageResponse").decode(buf)

            if(decodedResponse.messageData.ping){
                this.onPing(decodedResponse.messageData.ping,decodedResponse);
            } 
            if(decodedResponse.messageData.pong){
              this.onPong(decodedResponse.messageData.pong,decodedResponse);
            }
           
            console.log('rsp消息',decodedResponse);
            
            
          } catch (err) {
            console.log("出错",err);
         
          }
        }
        
    },
    sendmsg() {
      
      console.log("消息内容:",this.input);
    },
    createreq(messageData) {
      const MessageRequest = protoRoot.lookup("pb.app.MessageRequest");
      let timestamp = new Date().getTime();
      let data =  {
        messageData: messageData, // 请求数据
        timestamp: timestamp, // 客户端时间戳
        version: '4', // api版本号
        unique:''+ timestamp, // 请求唯一标示
      };
      console.log("预发送的数据:",data);
      const req = MessageRequest.create(data);
      let buffer = MessageRequest.encode(req).finish();
      return buffer;
    },
  },
  created() {
    this.wsob = new WebSocket("ws://192.168.169.2:32769");
    this.wsob.onopen = () => {
      console.log("成功建立连接");
      // Web Socket 已连接上，使用 send() 方法发送数据
      this.onopen();
      // ws.send("发送数据");
    };
    this.wsob.onmessage = (event) => {
      console.log("收到消息", event);
      this.onmessage(event.data);
    };
    this.wsob.onclose = () => {
      // 关闭 websocket
      console.log("连接已关闭...");
      this.onclose();
    };
    // console.log();
  },
};
</script>

<style>
.ping{
  color: red;
}
</style>
